# -*- coding: utf8 -*-
import os
import jinja2
import webapp2
import json

from game_template import *
from game_history import *
from random import *

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'])


class OneResult():
    def __init__(self, partner='', explained=0, guessed=0):
        self.partner = partner
        self.explained = explained
        self.guessed = guessed
        self.explained_words = []
        self.guessed_words = []
        self.accounted = False
        self.id = randint(100000, 999999)

    def add_explained(self, s, round_id=0):
        self.explained += 1
        self.explained_words.append(str(round_id) + ': ' + s)

    def add_guessed(self, s, round_id=0):
        self.guessed += 1
        self.guessed_words.append(str(round_id) + ': ' + s)

    def set_accounted(self):
        self.accounted = True

    def is_free(self):
        return not(self.accounted)


class PairResult():
    def __init__(self, player_1='', player_2='',
                 first_explained=0, first_guessed=0,
                 first_explained_words=[],
                 second_explained_words=[]):
        self.player_1 = player_1
        self.player_2 = player_2
        self.first_explained = first_explained
        self.first_guessed = first_guessed
        self.first_explained_words = first_explained_words
        self.second_explained_words = second_explained_words
        self.pair_id = randint(100000, 999999)
        self.sum = 0

    def count_sum(self):
        self.sum = self.first_explained + self.first_guessed


def gen_pair_results(game):
        gresult = dict()
        for result in game.guess_results:
            player1 = game.players[game.rounds[result.round_].player_explain]
            player2 = game.players[game.rounds[result.round_].player_guess]
            gresult[player1] = OneResult(partner=player2)
        for result in game.guess_results:
            player1 = game.players[game.rounds[result.round_].player_explain]
            player2 = game.players[game.rounds[result.round_].player_guess]
            if result.result == WordGuessResult.GUESS:
                gresult[player1].add_explained(game.words[result.word].text,
                                               result.round_ + 1)
        pair_results = []
        for result in gresult:
            cur_partner = gresult[result].partner
            if not(cur_partner) in gresult or gresult[cur_partner].is_free():
                if cur_partner in gresult:
                    second_explained = gresult[gresult[result].
                                               partner].explained
                else:
                    second_explained = 0
                first_explained_words = gresult[result].explained_words
                if cur_partner in gresult and gresult[cur_partner].is_free():
                    second_explained_words =\
                        gresult[gresult[result].partner].explained_words
                else:
                    second_explained_words = []
                a = PairResult(player_1=result,
                               player_2=gresult[result].partner,
                               first_explained=gresult[result].explained,
                               first_guessed=second_explained,
                               first_explained_words=first_explained_words,
                               second_explained_words=second_explained_words)
                a.count_sum()
                gresult[result].set_accounted()
                pair_results.append(a)

        pair_results = sorted(pair_results, key=lambda x: x.sum, reverse=True)
        return pair_results


def gen_single_results(game):
        gresult = dict()
        for result in game.guess_results:
            player1 = game.players[game.rounds[result.round_].player_explain]
            player2 = game.players[game.rounds[result.round_].player_guess]
            gresult[player1] = OneResult()
            gresult[player2] = OneResult()
        for result in game.guess_results:
            player1 = game.players[game.rounds[result.round_].player_explain]
            player2 = game.players[game.rounds[result.round_].player_guess]
            if result.result == WordGuessResult.GUESS:
                gresult[player1].add_explained(game.words[result.word].text,
                                               round_id=result.round_ + 1)
                gresult[player2].add_guessed(game.words[result.word].text,
                                             round_id=result.round_ + 1)
        for i in gresult:
            print(gresult[i].explained_words)

        return gresult


class CreateGameResults(webapp2.RequestHandler):
    def get(self):
        game_id = int(self.request.get("game_id"))
        try:
            game_pin = int(self.request.get("pin"))
        except:
            game_pin = 0000
        try:
            is_admin = int(self.request.get("judge"))
        except:
            is_admin = 0
        game = GameHistory.get_by_id(game_id)
        if game is None:
            self.error(404)
            self.response.write('ERROR 404: no game with such number')
        else:
            games = GameHistory.get_by_ids(game_id)
            result = []
            game_number = 0
            for game in games:
                game_number += 1
                if game_pin is None:
                    pin_exists = 0
                else:
                    pin_exists = 1
                wrong_pin = 0
                if is_admin == 1 and pin_exists == 1:
                    if game_pin == game.pin:
                        wrong_pin = 0
                    else:
                        wrong_pin = 1
                        is_admin = 0
                unused_words = game.unused_words
                if len(unused_words) == 0:
                    unused_words.append(u'Все слова использованы')
                if game.is_paired is None:
                    paired_flag = False
                else:
                    paired_flag = True
                if not(paired_flag) or game.is_paired:
                    pair_results = gen_pair_results(game)
                    single_results = []
                    game_was_paired = True
                else:
                    pair_results = []
                    single_results = gen_single_results(game)
                    game_was_paired = False
                game_time = 0
                result.append(
                    {"unused_words": unused_words[:-1],
                     "last_unused_word": unused_words[-1],
                     "pairs": pair_results,
                     "singles": single_results,
                     "admin": is_admin,
                     "wrong_pin": wrong_pin,
                     "paired": game_was_paired,
                     "game_time": game_time,
                     "key": game_id,
                     "game_time": game_time,
                     "game_type": GameHistory.str_repr_type[game.game_type],
                     "game_number": game_number})

            template = JINJA_ENVIRONMENT.get_template('game_results.html')
            self.response.write(
                template.render({"result": result}))


class CreateManyGamesResults(webapp2.RequestHandler):
    def get(self):
        game_ids = self.request.get("game_ids")
        unused_words = None
        pair_results = []
        for game_id_str in game_ids.split(","):
            game_id = int(game_id_str.strip())
            game = GameHistory.get_by_id(game_id)
            pair_results += gen_pair_results(game)
            if unused_words is None:
                unused_words = set(game.unused_words)
            else:
                unused_words &= set(game.unused_words)
        if len(unused_words) == 0:
            unused_words.add(u'Все слова использованы')
        template = JINJA_ENVIRONMENT.get_template('game_results.html')
        unused_words = list(unused_words)
        pair_results = sorted(pair_results, key=lambda x: x.sum, reverse=True)
        self.response.write(
            template.render(
                {"unused_words": unused_words[:-1],
                 "last_unused_word": unused_words[-1],
                 "pairs": pair_results}))
